#!/usr/bin/env node

// 天气预报
// const http = require('http');
// const addr = 'http://t.weather.sojson.com/api/weather/city/101090101';

// http.get(addr, res => {
//     res.pipe(process.stdout);
// });
// 增加命令行参数，参数是哪个城市中文名用key--value，就出现哪个城市的天气
// 查询结果表格输出


const http = require('http');
const fs = require('fs');

// 城市代码映射
const cityCode = {
  '北京': 101010100,
  '上海': 101020100,
  '天津': 101030100,
  '重庆': 101040100,
  '香港': 101320101,
  '澳门': 101330101,
  '石家庄': 101090101,
};

// 解析命令行参数
const args = process.argv.slice(2);
let city = args[0];
let code = cityCode[city];

if (!code) {
  console.error('未知的城市，请使用正确的城市名');
  process.exit(1);
}

// 构建请求URL
const url = `http://t.weather.sojson.com/api/weather/city/${code}`;

http.get(url, res => {
    let data = '';
  
    res.on('data', chunk => {
      data += chunk;
    });
  
    res.on('end', () => {
      try {
        const weatherData = JSON.parse(data);
        if (weatherData.status === 200) {
          console.log(`城市：${weatherData.cityInfo.city}`);
          console.log('日期\t天气\t最高温度\t最低温度\t风向\t风力');
          console.log('-------------------------------------------------');
          weatherData.data.forecast.forEach((day, index) => {
            console.log(`${day.date}\t${day.type}\t${day.high}℃\t${day.low}℃\t${day.fx}\t${day.fl}`);
          });
        } else {
          console.error('获取天气数据失败');
        }
      } catch (error) {
        console.error('解析天气数据错误');
      }
    });
  }).on('error', err => {
    console.error(`请求失败: ${err.message}`);
});